package com.amigo.online.provider.merchant.aspect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.provider.merchant.exception.CommonException;
import com.amigo.online.provider.merchant.exception.GoodsException;
import com.amigo.online.provider.merchant.exception.MerchantException;
import com.amigo.online.provider.merchant.service.CommonCheckService;

@Aspect
@Order(0) // 多个Aspect 顺序越小越先执行！
@Component
public class CommonCheckAopAction {

    @Autowired
    CommonCheckService commmonCheckService;

    private static final Logger logger = LoggerFactory.getLogger(CommonCheckAopAction.class);

    /**
     * @Title: pointCutMethod @Description: (定义Controller拦截规则) @param: @return:
     * void @throws
     */
    @Pointcut("@annotation(com.amigo.online.provider.merchant.aspect.CommonCheck)")
    private void pointCutMethod() {

    }

    @Before(value = "pointCutMethod() && @annotation(CommonCheck)", argNames = "CommonCheck") // 使用上面定义的切入点
    public void check(JoinPoint joinPoint, CommonCheck commonCheck) {
        Object[] args = joinPoint.getArgs();
        String[] methods = commonCheck.methods();
        String[] parameters = commonCheck.parameters();
        Method[] commonMethods = commmonCheckService.getClass().getMethods();
        Map<String, Method> methodMap = new HashMap<>(12);
        for (Method temp : commonMethods) {
            methodMap.put(temp.getName(), temp);
        }
        try {
            for (int i = 0; i < methods.length; i++) {
                String parameterString = parameters[i];
                String[] parametersIndex = parameterString.split(",");
                Method method = methodMap.get(methods[i]);
                if (method != null) {
                    Object[] methodParam = new Object[method.getParameterTypes().length];
                    for (int j = 0; j < parametersIndex.length; j++) {
                        int index = Integer.valueOf(parametersIndex[j]);
                        if (index > args.length) {
                            logger.error("AOP参数异常,下标越界!");
                            throw new CommonException(StatusCode.GOODS_NOT_BELONG_THIS_MERCHANT);
                        }
                        methodParam[j] = args[index - 1];
                    }
                    method.invoke(commmonCheckService, methodParam);
                }
            }
        } catch (NumberFormatException e) {
            logger.error("参数转化异常,args的参数参数不规范");
        } catch (SecurityException e) {
            logger.error("");
        } catch (IllegalAccessException e) {
            logger.error("参数不规范");
            throw new MerchantException(StatusCode.MERCHANT_NOT_MANAGER);
        } catch (IllegalArgumentException e) {
            logger.error("args的参数参数不规范");
            throw new MerchantException(StatusCode.MERCHANT_NOT_MANAGER);
        } catch (InvocationTargetException e) {
            try {
                logger.error("通用校验异常信息:{}", e.getTargetException());
                throw e.getTargetException();
            } catch (MerchantException merchantException) {
                throw merchantException;
            } catch (GoodsException goodsException) {
                throw goodsException;
            } catch (Throwable e1) {
                logger.error("通用校验类原异常!,异常信息为:{}", e1);
            }
        }
    }
}
